﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Json;

namespace Jermaine.Serialization
{
    /// <summary>
    /// JsonSerializer
    /// </summary>
    public class JsonSerializer : AbstractSerializer, ISerializer
    {
        public JsonSerializer() : base() { }


        public void Serialize<T>(string path, T o) where T : new() {
            base.IsNull(o);

            using (var stream = new FileStream(path, FileMode.Create)) {
                var ser = new DataContractJsonSerializer(o.GetType());
                ser.WriteObject(stream, o);
            }

        }


        public T Deserailize<T>(string path) {
            base.PathExists(path);
            var type = typeof(T);

            using (var stream = new FileStream(path, FileMode.Open)) {
                var ser = new DataContractJsonSerializer(type);
                return (T)ser.ReadObject(stream);
            }

        }


        public string Format<T>(T o) {

            using (var stream = new MemoryStream()) {
                var ser = new DataContractJsonSerializer(typeof(T));
                ser.WriteObject(stream, o);
                return Encoding.Default.GetString(stream.ToArray());
            }

        }

        public T Parse<T>(string stringObject) {

            var bytes = Encoding.Default.GetBytes(stringObject);
            using (var stream = new MemoryStream(bytes)) {
                var ser = new DataContractJsonSerializer(typeof(T));
                return (T)ser.ReadObject(stream);
            }
        }
    }
}
